import { defineStore } from "pinia";
import { ref } from "vue";

//local storage 的键名
const STORAGE_KEY = 'user_data'

const DEFAULT_ADMIN = {
    id: 'admin',
    username:'admin',
    password: 'admin123',
    role: 'admin',
    name: '系统管理员'
}

//将数据保存到local storage
const saveUsers = (users) => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(users))
}

//从local storage 中读取数据
const loadUsers = () =>{
    try{const storedData = localStorage.getItem(STORAGE_KEY)
    const users =  storedData ? JSON.parse(storedData):[]

    if(!users.some(user => user.role === 'admin')){
        users.push(DEFAULT_ADMIN)
        saveUsers(users)
    }
    return users
}catch (error) {
    console.error('Error loading users from localStorage:', error)
    return []
}
}

export const useMemberStore = defineStore('member', () => {
    const users = ref (loadUsers())

    const addUser = (user) => {
        user.id = Date.now()
        user.grades = {
            frontend: null,
            english: null,
            pyhon: null
        }
        users.value.push(user)
        saveUsers(users.value)
        
    }

    const updateUser = (id,updateInfo) => {
        const user = users.value.find((u) => u.id === id)
        if(user){
            Object.assign(user, updateInfo)
            saveUsers(users.value)
        }
    }

    const getUserById = (id) => {
        return users.value.find((u) => u.id === id)
    }

    const getUserByUsername = (username) => {
        return users.value.find((u) => u.username === username)
    }

    const deleteUser = (id) => {
        users.value = users.value.filter((u) => u.id !== id)
        saveUsers(users.value) 
    }

    const getAllStudents = () => {
        return users.value.filter((u) => u.role === 'student')
    }

    return{
        users,
        addUser,
        updateUser,
        getUserById,
        getUserByUsername,
        deleteUser,
        getAllStudents
    }
})